<?
/**
 * 배추 모바일 빌더 (Mobile for Gnuboard4)
 *
 * Copyright (c) 2010 Choi Jae-Young <www.miwit.com>
 *
 * 저작권 안내
 * - 저작권자는 이 프로그램을 사용하므로서 발생하는 모든 문제에 대하여 책임을 지지 않습니다. 
 * - 이 프로그램을 어떠한 형태로든 재배포 및 공개하는 것을 허락하지 않습니다.
 * - 이 저작권 표시사항을 저작권자를 제외한 그 누구도 수정할 수 없습니다.
 */

if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가

$is_dhtml_editor = false;

if ($w == '' && $content == $board['bo_insert_content']) {
    $content = '';
}

// 컨텐츠샵 멤버쉽
if (function_exists("mw_cash_is_membership")) {
    $is_membership = @mw_cash_is_membership($member[mb_id], $bo_table, "mp_write");
    if ($is_membership == "no")
        ;
    else if ($is_membership != "ok")
        mw_cash_alert_membership($is_membership);
        //alert("$is_membership 회원만 이용 가능합니다.");
}

if ($mw_basic[cf_must_notice]) { // 공지 필수
    $tmp_notice = str_replace("\n", ",", trim($board[bo_notice]));
    $cnt_notice = sizeof(explode(",", $tmp_notice));

    if ($tmp_notice) {
        $sql = "select count(*) as cnt from $mw[must_notice_table] where bo_table = '$bo_table' and mb_id = '$member[mb_id]' and wr_id in ($tmp_notice)";
        $row = sql_fetch($sql);
        if ($row[cnt] != $cnt_notice)
            alert("$board[bo_subject] 공지를 모두 읽으셔야 글작성이 가능합니다.");
    }
}

// 글작성 조건 
if (($w == "" || $w == "r") && $mw_basic[cf_write_point] && !$is_admin) {
    if ($member[mb_point] < $mw_basic[cf_write_point]) {
        alert("이 게시판은 $mw_basic[cf_write_point] 포인트 이상 소지자만 작성 가능합니다.");
    }
}
if (($w == "" || $w == "r") && $mw_basic[cf_write_register] && !$is_admin) {
    $gap = ($g4[server_time] - strtotime($member[mb_datetime])) / (60*60*24);
    if ($gap < $mw_basic[cf_write_register]) {
        alert("이 게시판은 가입후 $mw_basic[cf_write_register] 일이 지나야 작성 가능합니다.");
    }
}

// 글작성 제한
if (($w == "" || $w == "r") && $mw_basic[cf_write_day] && $mw_basic[cf_write_day_count] && !$is_admin) {
    $old = date("Y-m-d 00:00:00", $g4[server_time]-((60*60*24)*($mw_basic[cf_write_day]-1)));
    $sql = "select count(wr_id) as cnt from $write_table where mb_id = '$member[mb_id]' and wr_is_comment = '0' ";
    $sql.= "and wr_datetime between '$old' and '$g4[time_ymd] 23:59:59'";
    $row = sql_fetch($sql);

    if ($row[cnt] >= $mw_basic[cf_write_day_count]) {
        alert("이 게시판은 $mw_basic[cf_write_day]일에 $mw_basic[cf_write_day_count]번만 작성 가능합니다.");
    }
}

// 질문게시판
if ($mw_basic[cf_attribute] == 'qna' && $mw_basic[cf_qna_point_use] && $w == '') {
    if ($mw_basic[cf_qna_count] && !$is_admin) {
        $tmp = sql_fetch("select count(*) as cnt from $write_table where wr_qna_status = '0' and mb_id = '$member[mb_id]'");
        if ($tmp[cnt] >= $mw_basic[cf_qna_count]) {
            alert("이전에 작성하셨던 미해결 질문을 해결 또는 보류처리 해주셔야\\n\\n새로운 질문을 등록할 수 있습니다.",
                "./board.php?bo_table=$bo_table&sfl=mb_id&stx=$member[mb_id]");
        }
    }
}

if ($w == '' && trim($mw_basic[cf_insert_subject])) {
    $subject = $mw_basic[cf_insert_subject];
}

// 글수정 페이지의 첨부파일명 길이 조정
//--------------------------------------------------------------------------
// 가변 파일
$file_script = "";
$file_length = -1;
// 수정의 경우 파일업로드 필드가 가변적으로 늘어나야 하고 삭제 표시도 해주어야 합니다.
if ($w == "u")
{
    for ($i=0; $i<$file[count]; $i++)
    {
        $row = sql_fetch(" select bf_file, bf_content from $g4[board_file_table] where bo_table = '$bo_table' and wr_id = '$wr_id' and bf_no = '$i' ");
        if ($row[bf_file])
        {
            $file_script .= "add_file(\"&nbsp;&nbsp;<a href='#;' onclick='hiddenframe.location.href=\\\"{$file[$i][href]}\\\"'>".cut_str($file[$i][source], 20)."({$file[$i][size]})</a> <input type='checkbox' name='bf_file_del[$i]' value='1'> 파일 삭제하려면 체크하세요.";
            if ($is_file_content)
                //$file_script .= "<br><input type='text' class=ed size=50 name='bf_content[$i]' value='{$row[bf_content]}' title='업로드 이미지 파일에 해당 되는 내용을 입력하세요.'>";
                // 첨부파일설명에서 ' 또는 " 입력되면 오류나는 부분 수정
                $file_script .= "<br><input type='text' name='bf_content[$i]' value='".addslashes(get_text($row[bf_content]))."' title='업로드 이미지 파일에 해당 되는 내용을 입력하세요.' class='form-control'>";
            $file_script .= "\");\n";
        }
        else
            $file_script .= "add_file('');\n";
    }
    $file_length = $file[count] - 1;
}
if ($file_length < 0)
{
    $file_script .= "add_file('');\n";
    $file_length = 0;
}

if ($w == "") {  // 첨부파일 기본갯수
    for ($i=0; $i<$mw_basic[cf_attach_count]-1; $i++) {
        $file_script .= "add_file();\n";
    }   
}


?>

<link type="text/css" href="<?=$pc_skin_path?>/mw.js/ui-lightness/jquery-ui-1.8.19.custom.css" rel="stylesheet" />
<script type="text/javascript" src="<?=$pc_skin_path?>/mw.js/jquery-ui-1.8.19.custom.min.js"></script>

<style type="text/css">
#mw_mobile .board_write {
    list-style:none;
    margin:5px;
    padding:5px;
    box-shadow: 0 1px #EBEBEB;
    border-radius: 3px;
    border: 1px solid;
    border-color: #E5E5E5 #D3D3D3 #B9C1C6;
    background-color:#fff;
}
.write_head { width:50px; height:30px; text-align:center; color:#8492A0; }
.field { border:1px solid #ccc; }
</style>

<script language="javascript">
// 글자수 제한
var char_min = parseInt(<?=$write_min?>); // 최소
var char_max = parseInt(<?=$write_max?>); // 최대
</script>

<div class="board_write">

<form name="fwrite" method="post" onsubmit="return fwrite_submit(this);" style="margin:0px;" enctype="multipart/form-data" class="form-horizontal" role="form">
<input type=hidden name=null> 
<input type=hidden name=w        value="<?=$w?>">
<input type=hidden name=bo_table value="<?=$bo_table?>">
<input type=hidden name=wr_id    value="<?=$wr_id?>">
<input type=hidden name=sca      value="<?=$sca?>">
<input type=hidden name=sfl      value="<?=$sfl?>">
<input type=hidden name=stx      value="<?=$stx?>">
<input type=hidden name=spt      value="<?=$spt?>">
<input type=hidden name=sst      value="<?=$sst?>">
<input type=hidden name=sod      value="<?=$sod?>">
<input type=hidden name=page     value="<?=$page?>">
<?
// 익명게시판
if ($mw_basic[cf_attribute] == "anonymous" && $is_guest) {
    $is_name = $is_email = $is_homepage = false;
    echo "<input type=hidden name=wr_name value='익명'>\n";
}
?>

<? if ($is_name) { ?>
<div class="form-group">
    <label for="wr_name" class="col-lg-2 control-label">이름</label>
    <div class="col-lg-10">
        <input type="text" class="form-control" id="wr_name" name="wr_name" maxlength="20" itemname="이름" placeholder="이름" required value="<?=$name?>">
    </div>
</div>
<? } ?>

<? if ($is_password) { ?>
<div class="form-group">
    <label for="wr_password" class="col-lg-2 control-label">패스워드</label>
    <div class="col-lg-10">
        <input type="password" class="form-control" id="wr_password" name="wr_password" maxlength="20" itemname="패스워드" placeholder="패스워드" required <?=$password_required?>>
    </div>
</div>
<? } ?>

<? if ($is_email) { ?>
<div class="form-group">
    <label for="wr_email" class="col-lg-2 control-label">이메일</label>
    <div class="col-lg-10">
        <input type="text" class="form-control" id="wr_email" name="wr_email" maxlength="100" itemname="이메일" placeholder="이메일" value="<?=$email?>">
    </div>
</div>
<? } ?>

<? if ($is_homepage) { ?>
<div class="form-group">
    <label for="wr_homepage" class="col-lg-2 control-label">홈페이지</label>
    <div class="col-lg-10">
        <input type="text" class="form-control" id="wr_homepage" name="wr_homepage" maxlength="100" itemname="홈페이지" placeholder="홈페이지" value="<?=$homepage?>">
    </div>
</div>
<? } ?>

<? 
$option = "";
$option_hidden = "";
if ($is_notice || $is_html || $is_secret || $is_mail || $mw_basic[cf_anonymous]) { 
    $option = "";
    if ($is_notice) { 
        $option .= "<label class=\"checkbox-inline\"><input type=\"checkbox\" id=\"notice\" name=\"notice\" value=\"1\" $notice_checked>공지</label>";
    }

    if ($is_html) {
        if ($is_dhtml_editor) {
            $option_hidden .= "<input type=hidden value='html1' name='html'>";
        }
        else {
            $option .= "<label class=\"checkbox-inline\"><input onclick='html_auto_br(this);' type=\"checkbox\" value='$html_value' name='html' id='html' $html_checked>html&nbsp;</label>";
        }
    }

    if ($is_secret) {
        if ($is_admin || $is_secret==1) {
            $option .= "<label class=\"checkbox-inline\"><input type=\"checkbox\" value=\"secret\" id=\"secret\" name=\"secret\" $secret_checked>비밀글&nbsp;</label>";
        } else {
            $option_hidden .= "<input type=\"hidden\" value=\"secret\" name=\"secret\">";
        }
    }
    
    if ($is_mail) {
        $option .= "<label  class=\"checkbox-inline\"><input type=\"checkbox\" value=\"mail\" id=\"mail\" name=\"mail\" $recv_email_checked>답변메일받기&nbsp;</label>";
    }

    if ($mw_basic[cf_anonymous]) {
        $option .= "<label class=\"checkbox-inline\"><input type=\"checkbox\" id=\"wr_anonymous\" name=\"wr_anonymous\" value=\"1\"> 익명</label>";
    }
}

echo $option_hidden;
if ($option) {
?>
<div class="form-group">
<tr>
    <label class="col-lg-2 control-label">옵션</label>
    <div class="col-lg-10"> <?=$option?> </div>
</div>
<? } ?>

<? if ($is_category) { ?>
<div class="form-group">
    <label for="ca_name" class="col-lg-2 control-label">분류</label>
    <div class="col-lg-10">
        <select class="form-control" id="ca_name" name="ca_name" required itemname="분류"><option value="">선택하세요<?=$category_option?></select>
    </div>
</div>
<? } ?>

<div class="form-group">
    <label for="ca_name" class="col-lg-2 control-label">제목</label>
    <div class="col-lg-10">
        <input type="text" class="form-control" id="wr_subject" name="wr_subject" maxlength="100" itemname="제목" placeholder="제목" required value="<?=$subject?>">
    </div>
</div>

<div class="form-group">
    <label for="wr_content" class="col-lg-2 control-label">내용</label>
    <div class="col-lg-10">
        <div>
            <span style="cursor: pointer;" onclick="textarea_decrease('wr_content', 10);"><img src="<?=$board_skin_path?>/img/up.gif"></span>
            <span style="cursor: pointer;" onclick="textarea_original('wr_content', 10);"><img src="<?=$board_skin_path?>/img/start.gif"></span>
            <span style="cursor: pointer;" onclick="textarea_increase('wr_content', 10);"><img src="<?=$board_skin_path?>/img/down.gif"></span>
        <? if ($write_min || $write_max) { ?><span id=char_count></span>글자<?}?>
        </div>

        <textarea class="form-control" id="wr_content" name="wr_content" style='word-break:break-all;' rows="10" itemname="내용" required  placeholder="내용"
        <? if ($write_min || $write_max) { ?>onkeyup="check_byte('wr_content', 'char_count');"<?}?>><?=$content?></textarea>
        <? if ($write_min || $write_max) { ?><script> check_byte('wr_content', 'char_count'); </script><?}?>
    </div>
</div>

<? if ($mw_basic[cf_bomb_level] && $mw_basic[cf_bomb_time] && !$is_admin) { ?>
<div class="form-group">
    <label for="ca_name" class="col-lg-2 control-label">자동폭파 </label>
    <div class="col-lg-10">
        <?=$mw_basic[cf_bomb_time]?>시간 후 자동 폭파됩니다.
    </div>
</div>
<? } ?>

<? if ($mw_basic[cf_bomb_level] && $mw_basic[cf_bomb_level] <= $member[mb_level] && (!$mw_basic[cf_bomb_time] || $is_admin)) { ?>
<div class="form-group">
    <label for="ca_name" class="col-lg-2 control-label">자동폭파 </label>
    <div class="col-lg-10">
    <?
    $bomb = array();
    $bm_year_start = date("Y", $g4[server_time]);
    if ($w == 'u') {
        $bomb = sql_fetch(" select * from $mw[bomb_table] where bo_table = '$bo_table' and wr_id = '$wr_id' ");
        if (date("Y", strtotime($bomb[bm_datetime])) < date("Y", $g4[server_time])) {
            $bm_year_start = date("Y", strtotime($bomb[bm_datetime]));
        }
    }
    ?>
    <input type="button" class="btn btn-default btn-sm" style="padding:5px;" value="지금" onclick="bomb_cate_now()"/>
    <input type="button" class="btn btn-default btn-sm" style="padding:5px;" value="초기화" onclick="bomb_cate_init()"/>
    <input type="checkbox" name="bm_log" value="1">흔적 남기기
    <br/>
 
    <select name="bm_year">
        <option value=""></option>
        <? for ($i=$bm_year_start; $i<=date("Y", $g4[server_time])+1; $i++) { ?>
        <option value="<?=$i?>"><?=$i?></option>
        <? } ?>
    </select> 년
    <select name="bm_month">
        <option value=""></option>
        <? for ($i=1; $i<=12; $i++) { ?>
        <option value="<?=sprintf("%02d", $i)?>"><?=sprintf("%02d", $i)?></option>
        <? } ?>
    </select> 월
    <select name="bm_day">
        <option value=""></option>
        <? for ($i=1; $i<=31; $i++) { ?>
        <option value="<?=sprintf("%02d", $i)?>"><?=sprintf("%02d", $i)?></option>
        <? } ?>
    </select> 일 <br/> 
    <select name="bm_hour">
        <option value=""></option>
        <? for ($i=0; $i<=23; $i++) { ?>
        <option value="<?=sprintf("%02d", $i)?>"><?=sprintf("%02d", $i)?></option>
        <? } ?>
    </select> 시
    <select name="bm_minute">
        <option value=""></option>
        <? for ($i=0; $i<=59; $i++) { ?>
        <option value="<?=sprintf("%02d", $i)?>"><?=sprintf("%02d", $i)?></option>
        <? } ?>
    </select> 분 
    </div>
    <script type="text/javascript">
    function bomb_cate_now() {
        var d = new Date();

        d.setTime(d.getTime()+1000*60);
        yy = d.getFullYear();
        mm = (d.getMonth() + 1);
        dd = d.getDate();
        hh = d.getHours();
        ii = d.getMinutes();

        if (mm < 10) mm = '0' + mm;
        if (dd < 10) dd = '0' + dd;
        if (hh < 10) hh = '0' + hh;
        if (ii < 10) ii = '0' + ii;

        fwrite.bm_year.value = yy;
        fwrite.bm_month.value = mm;
        fwrite.bm_day.value = dd;
        fwrite.bm_hour.value = hh;
        fwrite.bm_minute.value = ii;
    }
    function bomb_cate_init() {
        fwrite.bm_year.value = '';
        fwrite.bm_month.value = '';
        fwrite.bm_day.value = '';
        fwrite.bm_hour.value = '';
        fwrite.bm_minute.value = '';
    }
    <? if ($bomb) { ?>
    fwrite.bm_year.value = '<?=date("Y", strtotime($bomb[bm_datetime]))?>';
    fwrite.bm_month.value = '<?=date("m", strtotime($bomb[bm_datetime]))?>';
    fwrite.bm_day.value = '<?=date("d", strtotime($bomb[bm_datetime]))?>';
    fwrite.bm_hour.value = '<?=date("H", strtotime($bomb[bm_datetime]))?>';
    fwrite.bm_minute.value = '<?=date("i", strtotime($bomb[bm_datetime]))?>';
    fwrite.bm_log.checked = '<?=$bomb[bm_log]?>';
    <? } ?>
    </script>
</div>

<? } ?>

<? if ($mw_basic[cf_google_map]) { ?>
<div class="form-group">
    <label for="wr_google_map" class="col-lg-2 control-label">지도삽입</label>
    <div class="col-lg-10">

        <input class="form-control" name="wr_google_map" id="wr_google_map" itemname="지도삽입 주소" placeholder="지도삽입 주소" value="<?=$write[wr_google_map]?>">
        <div class="help-block">(본문에 {구글지도} 라고 입력하면 원하는 위치에 구글지도가 삽입됩니다.)</div>
        <input type="button" value="주소확인" class="btn1" onclick="win_google_map()">

        <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
        <script src="<?=$pc_skin_path?>/mw.js/mw.google.js"></script>
        <script>
        function win_google_map() {
            $("#google-map").css("display", "none");
            $("#dialog-map").dialog("close");
            $("#dialog-map").dialog({
                width: 300,
                height: 300,
                autoOpen: false,
                //modal: true,
                resizable: true,
                buttons: {
                    "닫기": function () {
                        $("#google-map").css("display", "none");
                        $(this).dialog("close");
                    }
                }
            });
            $("#dialog-map").dialog("open");
            $("#google-map").css("display", "block");
            $("#google-map").html("");
            mw_google_map("google-map", $("#wr_google_map").val());
        }
        </script>

        <div id="dialog-map" class="dialog-content">
            <div id="google-map" style="border:1px solid #999; width:250px; height:170px; margin:10px; display:none;"></div>
        </div>
 
    </div>
</div>
<? } ?>

<?  if ($mw_basic[cf_attribute] == 'qna' && $mw_basic[cf_qna_point_use]) { ?>
<div class="form-group">
    <label for="wr_google_map" class="col-lg-2 control-label">질문포인트</label>
    <div class="col-lg-10">

        <input type="text" class="form-control" id="wr_qna_point" name="wr_qna_point" required numeric value="<?=$write[wr_qna_point]?>" itemname="질문 포인트"  placeholder="질문 포인트" <? if (!$is_admin && $w == 'u') echo "disabled"; ?> >
        <div class="help-block"> 포인트. 질문자 포인트(<?=number_format($member[mb_point])?>)에서 차감<br/>
    (<?=$mw_basic[cf_qna_point_min]?>~<?=$mw_basic[cf_qna_point_max]?>점, 채택자 <?=$mw_basic[cf_qna_save]?>% 적립, 수정불가) </div>
    </div>
</div>
<? if ($is_admin) { ?>
<div class="form-group">
    <label for="wr_qna_status" class="col-lg-2 control-label">질문상태</label>
    <div class="col-lg-10">
        <select class="form-control" id="wr_qna_status" name="wr_qna_status">
            <option value=""> </option>
            <option value="0"> 미해결 </option>
            <option value="1"> 해결 </option>
            <option value="2"> 보류 </option>
        </select>
        <div class="help-block"> 관리자 전용 </div>
        <script> document.fwrite.wr_qna_status.value = "<?=$write[wr_qna_status]?>"; </script>
    </div>
</div>
<? } ?>
<? } ?>

<?  if ($mw_basic[cf_read_level] && $mw_basic[cf_read_level_own] <= $member[mb_level]) { ?>
<div class="form-group">
    <label for="change_image_size" class="col-lg-2 control-label">글읽기 레벨</label>
    <div class="col-lg-10">
        <select name="wr_read_level" class="mw_basic_text" itemname="글읽기 레벨">
        <option value=""> </option>
        <? for ($i=1; $i<=$member[mb_level]; $i++) { ?>
        <option value="<?=$i?>"> <?=$i?> </option>
        <? } ?>
        </select>
        <script> fwrite.wr_read_level.value = "<?=$write[wr_read_level]?>"; </script>
    </div>
</div>
<? } ?>

<? if ($mw_basic[cf_change_image_size] && $member[mb_level] >= $mw_basic[cf_change_image_size_level]) { ?>
<div class="form-group">
    <label for="change_image_size" class="col-lg-2 control-label">크기변경</label>
    <div class="col-lg-10">
        <input type="text" class="form-control" id="change_image_size" name="change_image_size" itemname="첨부이미지 크기변경" placeholder="첨부이미지 크기변경" value="<?=$change_image_size?>" class=mw_basic_text>
        <div class="help-block"> px. 첨부이미지 크기를 변경합니다, 작게만 가능. </div>
    </div>
</div>
<? } ?>

<? if ($is_file && !($mw_basic[cf_guploader] && $is_member)) { ?>
<div class="form-group">
    <label for="bf_file_0" class="col-lg-2 control-label">
        <? if ($mw_basic[cf_zzal]) echo "짤방"; else echo "파일"; ?>
        <span onclick="add_file();" style='cursor:pointer; font-family:tahoma; font-size:12pt;'>+</span>
        <span onclick="del_file();" style='cursor:pointer; font-family:tahoma; font-size:12pt;'>-</span>
    </label>
    <div class="col-lg-10">
        <table id="variableFiles"></table><?// print_r2($file); ?>
	<? if ($mw_basic[cf_img_1_noview]) { ?>
	첫번째 첨부파일은 썸네일로만 출력됩니다. 본문에 출력되지 않습니다. 
        <? } else if ($mw_basic[cf_zzal] && $mw_basic[cf_zzal_must]) { ?>
        반드시 첫번째에 짤방 이미지를 첨부하셔야 합니다.
        <? } ?>
        <script type="text/javascript">
        var flen = 0;
        function add_file(delete_code)
        {
            var upload_count = <?=(int)$board[bo_upload_count]?>;
            if (upload_count && flen >= upload_count)
            {
                alert("이 게시판은 "+upload_count+"개 까지만 파일 업로드가 가능합니다.");
                return;
            }

            var objTbl;
            var objRow;
            var objCell;
            if (document.getElementById)
                objTbl = document.getElementById("variableFiles");
            else
                objTbl = document.all["variableFiles"];

            objRow = objTbl.insertRow(objTbl.rows.length);
            objCell = objRow.insertCell(0);

            objCell.innerHTML = "<input type='file' class='form-control' id='bf_file_" + flen + "' name='bf_file[]' title='파일 용량 <?=$upload_max_filesize?> 이하만 업로드 가능'>";

	    /*
	    str = "<input type='file' id=bf_file_" + flen + " name='bf_file[]' title='파일 용량 <?=$upload_max_filesize?> 이하만 업로드 가능' class=mw_basic_text> ";
	    str+= " <input type='button' value='본문에 넣기' onclick=\"document.getElementById('wr_content').value += '{이미지:" + flen + "}'\"";
	    objCell.innerHTML = str;
	    */

            if (delete_code)
                objCell.innerHTML += delete_code;
            else
            {
                <? if ($is_file_content) { ?>
                objCell.innerHTML += "<br><input type='text' name='bf_content[]' title='업로드 이미지 파일에 해당 되는 내용을 입력하세요.' class='form-control'>";
                <? } ?>
                ;
            }

            flen++;
        }

        <?=$file_script; //수정시에 필요한 스크립트?>

        function del_file()
        {
            // file_length 이하로는 필드가 삭제되지 않아야 합니다.
            var file_length = <?=(int)$file_length?>;
            var objTbl = document.getElementById("variableFiles");
            if (objTbl.rows.length - 1 > file_length)
            {
                objTbl.deleteRow(objTbl.rows.length - 1);
                flen--;
            }
        }
        </script>
    </div>
</div>
<? } ?>

<? if ($mw_basic[cf_related]) { ?>
<div class="form-group">
    <label for="wr_related" class="col-lg-2 control-label">관련글 키워드</label>
    <div class="col-lg-10">
        <input type="text" class="form-control" id="wr_related" name="wr_related" itemname="관련글 키워드" value="<?=$write[wr_related]?>"> 
        <div class="help-block">키워드를 , 컴마로 구분하여 입력해주세요. (예 : 한예슬, 얼짱, 몸짱)</div>
    </div>
</div>
<? } ?>

<? if ($mw_basic[cf_comment_ban] && $mw_basic[cf_comment_ban_level] <= $member[mb_level]) { ?>
<div class="form-group">
    <label for="wr_comment_ban" class="col-lg-2 control-label">코멘트 금지</label>
    <div class="col-lg-10">
        <input type="checkbox" id="wr_comment_ban" name="wr_comment_ban" value="1"> (코멘트를 원하지 않을 경우 체크해주세요.)
        <script> document.fwrite.wr_comment_ban.checked = "<?=$write[wr_comment_ban]?>" </script>
    </div>
</div>
<? } ?>

<? if ($mw_basic[cf_ccl]) { ?>
<div class="form-group">
    <label for="wr_comment_ban" class="col-lg-2 control-label">CCL</label>
    <div class="col-lg-10">
        <select name="wr_ccl_by">
            <option value="">사용안함</option>
            <option value="by">사용</option>
        </select>
        영리목적 : <select name="wr_ccl_nc">
            <option value="nc">사용불가</option>
            <option value="">사용가능</option>
        </select>
        변경 : <select name="wr_ccl_nd">
            <option value="nd">변경불가</option>
            <option value="sa">동일조건변경가능</option>
            <option value="">변경가능</option>
        </select>
        <a href="http://www.creativecommons.or.kr/info/about" target=_blank>CCL이란?</a>
        <? if ($w == "u") {?>
        <script>
        document.fwrite.wr_ccl_by.value = "<?=$write[wr_ccl][by]?>";
        document.fwrite.wr_ccl_nc.value = "<?=$write[wr_ccl][nc]?>";
        document.fwrite.wr_ccl_nd.value = "<?=$write[wr_ccl][nd]?>";
        </script>
        <? } ?>
    </div>
</div>
<? } ?>

<? if ($is_link) { ?>
<? for ($i=1; $i<=$g4[link_count]; $i++) { ?>
<div class="form-group">
    <label for="wr_link<?=$i?>" class="col-lg-2 control-label">링크 #<?=$i?></label>
    <div class="col-lg-10">

    <input type="text" class="form-control" id="wr_link<?=$i?>" name="wr_link<?=$i?>" itemname="링크 #<?=$i?>" value="<?=$write["wr_link{$i}"]?>">
    <? if ($mw_basic[cf_link_target_level] && $mw_basic[cf_link_target_level] <= $member[mb_level]) { ?>
        <select name="wr_link<?=$i?>_target">
            <option value="_blank">새창 (_blank)</option>
            <option value="_self">현재창 (_self)</option>
        </select>
        <script> fwrite.wr_link<?=$i?>_target.value = "<?=$write["wr_link{$i}_target"]?>"; </script>
    <? } ?>
    <? if ($mw_basic[cf_link_write] && $mw_basic[cf_link_write] <= $member[mb_level] && $i == 1) { ?>
        <br/>
        <input type="checkbox" name="wr_link_write" value="1" <? if ($write[wr_link_write]) echo "checked"; ?> >
        본문 출력 없이 링크로 바로 이동
    <? } ?>
    </div>
</div>
<? } ?>
<? } ?>

<? if ($is_guest) { ?>
<div class="form-group">
    <label for="wr_key" class="col-lg-2 control-label">자동등록방지</label>
    <div class="col-lg-10">
        <img id='kcaptcha_image' align="left"/>
        <div><input type="text" id="wr_key" name="wr_key" itemname="자동등록방지" required></div>
        <div>왼쪽의 글자를 입력하세요.</div>
    </div>
</div>
<? } ?>

</table>

<div style="padding:30px 0 30px 0; text-align:center;">
    <input type="submit" class="btn btn-default btn-sm" value="글쓰기">&nbsp;
    <input type="button" class="btn btn-default btn-sm" value="임시저장" onclick="mw_save_temp('임시 저장 했습니다.')">&nbsp;
    <input type="button" class="btn btn-default btn-sm" value="취소" onclick="history.back()">
    <input type="button" class="btn btn-default btn-sm" value="목록"
        onclick="location.href='<?php echo mw_seo_url($bo_table, 0, $qstr)?>'">
</div>

</form>

</div>

<script src="jquery.kcaptcha.js"></script>
<script>
$(document).ready(function () {
    if (typeof(document.fwrite.ca_name) != 'undefined') {
        fwrite.ca_name.value = "<?=$sca?>";
    }

    <?
    // 관리자라면 분류 선택에 '공지' 옵션을 추가함
    if ($is_admin)
    {
        echo "
        if (typeof(document.fwrite.ca_name) != 'undefined')
        {
            document.fwrite.ca_name.options.length += 1;
            document.fwrite.ca_name.options[document.fwrite.ca_name.options.length-1].value = '공지';
            document.fwrite.ca_name.options[document.fwrite.ca_name.options.length-1].text = '공지';
        }";
    }
    ?>

    with (document.fwrite) {
        if (typeof(wr_name) != "undefined")
            wr_name.focus();
        else if (typeof(wr_subject) != "undefined")
            wr_subject.focus();
        else if (typeof(wr_content) != "undefined")
            wr_content.focus();

        if (typeof(ca_name) != "undefined") {
                if (w.value == "u")
                    ca_name.value = "<?=$write[ca_name]?>";
        }
    } 


    <? if ($w == "" && $is_member) { ?>
    $.post("<?=$board_skin_path?>/mw.proc/mw.temp.php", 
        {
            "w": "get",
            "bo_table": "<?=$bo_table?>"
        },
        function(data) {
            data = data.split("-mw-basic-temp-return-");
            if (data[1] && confirm("임시 저장한 내용이 있습니다.\n\n불러오시겠습니까?")) {
                $("#wr_subject").val(data[0]);
                $("#wr_content").val(data[1]);
                <? if ($is_dhtml_editor && $mw_basic[cf_editor] == "cheditor") { ?>
                document.getElementById('tx_wr_content').value = data[1];
                ed_wr_content.resetDoc();
                <? } else if ($is_dhtml_editor && $mw_basic[cf_editor] == "geditor") { ?>
                geditor_wr_content.update();
                <? } ?>
            }
        }
    );
    //$("#wr_content").focusout(function () { setTimeout(mw_save_temp, 100); });
    //$("#wr_subject").focusout(function () { setTimeout(mw_save_temp, 100); });
    <? } ?>

    /*window.onbeforeunload = function () {
        <? if ($w == "") echo "mw_save_temp();"; ?>
        return "다른 페이지로 이동하시면 작성중인 글이 모두 사라집니다.";
    }*/
    $(window).bind('beforeunload', function () {
        return "다른 페이지로 이동하시면 작성중인 글이 모두 사라집니다.";
    });
});

function mw_save_temp(msg)
{
    <? if (!$is_member) echo "return;"; ?>
    var wr_subject = $("#wr_subject").val();
    var wr_content = $("#wr_content").val();

    <? if ($is_dhtml_editor && $mw_basic[cf_editor] == "cheditor") { ?>
    wr_content = ed_wr_content.outputBodyHTML();
    <? } ?>

    $.post("<?=$board_skin_path?>/mw.proc/mw.temp.php", {
        "w" : "save",
        "bo_table" : "<?=$bo_table?>",
        "wr_subject" : encodeURIComponent(wr_subject),
        "wr_content" : encodeURIComponent(wr_content)
    }, function (ret) {
        if (ret) { alert(ret); return; }
        if (msg) alert(msg);
    });
}

function html_auto_br(obj) 
{
    if (obj.checked) {
        result = confirm("자동 줄바꿈을 하시겠습니까?\n\n자동 줄바꿈은 게시물 내용중 줄바뀐 곳을<br>태그로 변환하는 기능입니다.");
        if (result)
            obj.value = "html2";
        else
            obj.value = "html1";
    }
    else
        obj.value = "";
}

function fwrite_submit(f) 
{
    /*
    var s = "";
    if (s = word_filter_check(f.wr_subject.value)) {
        alert("제목에 금지단어('"+s+"')가 포함되어있습니다");
        return false;
    }

    if (s = word_filter_check(f.wr_content.value)) {
        alert("내용에 금지단어('"+s+"')가 포함되어있습니다");
        return false;
    }
    */
    if (document.getElementById('char_count')) {
        if (char_min > 0 || char_max > 0) {
            var cnt = parseInt(document.getElementById('char_count').innerHTML);
            if (char_min > 0 && char_min > cnt) {
                alert("내용은 "+char_min+"글자 이상 쓰셔야 합니다.");
                return false;
            } 
            else if (char_max > 0 && char_max < cnt) {
                alert("내용은 "+char_max+"글자 이하로 쓰셔야 합니다.");
                return false;
            }
        }
    }

    if (document.getElementById('tx_wr_content')) {
        if (!ed_wr_content.outputBodyText()) { 
            alert('내용을 입력하십시오.'); 
            ed_wr_content.returnFalse();
            return false;
        }
    }

    var subject = "";
    var content = "";
    $.ajax({
        url: "<?=$board_skin_path?>/ajax.filter.php",
        type: "POST",
        data: {
            "subject": f.wr_subject.value,
            "content": f.wr_content.value
        },
        dataType: "json",
        async: false,
        cache: false,
        success: function(data, textStatus) {
            subject = data.subject;
            content = data.content;
        }
    });

    if (subject) {
        alert("제목에 금지단어('"+subject+"')가 포함되어있습니다");
        f.wr_subject.focus();
        return false;
    }

    if (content) {
        alert("내용에 금지단어('"+content+"')가 포함되어있습니다");
        if (typeof(ed_wr_content) != "undefined") 
            ed_wr_content.returnFalse();
        else 
            f.wr_content.focus();
        return false;
    }

    if (!check_kcaptcha(f.wr_key)) {
        return false;
    }

    /*if (typeof(f.wr_key) != 'undefined') {
        if (hex_md5(f.wr_key.value) != md5_norobot_key) {
            alert('자동등록방지용 글자가 제대로 입력되지 않았습니다.');
            f.wr_key.select();
            f.wr_key.focus();
            return false;
        }
    }*/

    <? if ($mw_basic[cf_zzal] && $mw_basic[cf_zzal_must]) { ?>
    var zzal = document.getElementById("bf_file_0").value;
    if (f.w.value=='' && !zzal)
    {
        alert("짤방 이미지를 입력해 주세요.");
        return false;
    }

    if (f.w.value=='' && !zzal.match(/.(gif|jpg|jpeg|png)$/i))
    {
        alert(document.getElementById("bf_file[]").value + ' 은(는) 이미지 파일이 아닙니다.');
        return false;
    }
    <? } ?>

    //document.getElementById('btn_submit').disabled = true;
    //document.getElementById('btn_list').disabled = true;

    <?
    if ($g4[https_url])
        echo "f.action = '$g4[https_url]/plugin/mobile/write_update.php';";
    else
        echo "f.action = './write_update.php';";
    ?>

    $(window).unbind('beforeunload');
    $(window).bind('beforeunload', function () {
        mw_save_temp();
    });

    return true;
}
</script>

<script language="JavaScript" src="<?="$g4[path]/js/board.js"?>"></script>
<script language="JavaScript"> window.onload=function() { drawFont(); } </script>

